package com.kaia.shoebox.fragment;

import java.util.Date;

import android.content.Intent;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;

import com.kaia.shoebox.Intents;
import com.kaia.shoebox.R;
import com.kaia.shoebox.activity.EditTodoActivity;
import com.kaia.shoebox.db.dao.Importance;
import com.kaia.shoebox.db.dao.TodoItem;

public class TodoListFragment extends BaseListFragment {

	private static final String TAG = TodoListFragment.class.getSimpleName();

	// ------------------------------------------------------------------
	// Overrides
	// ------------------------------------------------------------------

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {

		TodoItem selected = mAdapter.getItem(position);

		String title = selected.getTitle();
		Date dueDate = selected.getDueDate();
		String notes = selected.getNotes();
		Importance importance = selected.getImportance();

		Intent data = new Intent();
		data.setClass(getActivity(), EditTodoActivity.class);
		data.putExtra("_id", selected.getId());
		data.putExtra("title", title);
		data.putExtra("due", dueDate.getTime());
		data.putExtra("notes", notes);
		data.putExtra("importance", importance.getImportanceNumber());

		startActivityForResult(data, Intents.EDIT_TODO_INTENT);

		Log.i(TAG, "Sending result: EDIT_TODO:[_id=" + selected.getId()
				+ "title=" + title + ", due=" + dueDate.getTime() + ", notes="
				+ notes + ", importance=" + importance.getImportanceNumber());
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getActivity().getMenuInflater();
		inflater.inflate(R.menu.item_context_menu, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		switch (item.getItemId()) {
		case R.id.item_delete:
			deleteTodo((int) info.id);
			return true;
		case R.id.item_done:
			return true;
		default:
			return super.onContextItemSelected(item);
		}

	}

	// ------------------------------------------------------------------
	// Utility Methods
	// ------------------------------------------------------------------

	public void updateTodo(TodoItem newItem) {
		mAdapter.update(newItem, newItem.getId());
	}
}
